package com.example.demo.demos.web;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 *  防腐层适配器
 *  避免一个服务修改了代码，影响另一个服务
 */
@Component
public class AntisepticAdapter {

    private static final Logger logger = LoggerFactory.getLogger(AntisepticAdapter.class);

    @Resource
    private BasicController basicController;

    public User login(String username, String password) throws IllegalAccessException {
        if (StringUtils.isBlank(username)) {
            throw new IllegalAccessException("用户名不能为空");
        }
        long t1 = System.currentTimeMillis();
        //远程调用
        User user = User.builder()
                .name(username).build();
        //从其他十几二十个类中远程调用 basicController.user(); 修改为注入防腐适配器类，
        // 从而达到假设修改User内部参数等不需要修改十几二十个地方
        User u = basicController.user();

        long t2 = System.currentTimeMillis();
        //打印慢接口日志
        if (t2 - t1 > 3000L) {
            logger.warn("调用外部接口耗时过长，cost:[{}]ms", t2 - t1);
        }

        if (u == null) {
            throw new RuntimeException("登录用户" + username + "不存在");
        }
        return u;
    }
}
